import React, { useEffect } from 'react';
import { useAppStore } from '../stores/appStore';

interface GlobalShortcutsProps {
  shortcuts: {
    toggleVisibility: string;
    increaseOpacity: string;
    decreaseOpacity: string;
    toggleDisguise: string;
  };
}

const GlobalShortcuts: React.FC<GlobalShortcutsProps> = ({ shortcuts }) => {
  const { 
    opacity, 
    setOpacity, 
    isVisible, 
    setIsVisible, 
    currentMode, 
    setCurrentMode 
  } = useAppStore();

  // 注册全局快捷键（暂时禁用，避免错误）
  const registerShortcuts = async () => {
    console.log('🎹 全局快捷键注册已暂时禁用，使用浏览器内键盘事件监听');
    console.log('📋 配置的快捷键:', shortcuts);
    
    // TODO: 修复全局快捷键注册问题后重新启用
    // 暂时注释掉全局快捷键注册，避免错误弹窗
    /*
    try {
      console.log('🔧 注册切换可见性快捷键:', shortcuts.toggleVisibility);
      await safeTauriInvoke('register_global_shortcut', {
        shortcut: shortcuts.toggleVisibility,
        action: 'toggle_visibility'
      });
      console.log('✅ 切换可见性快捷键注册成功');
      
      // ... 其他快捷键注册
    } catch (error) {
      console.error('❌ 全局快捷键注册失败:', error);
      // 不再显示弹窗，只在控制台记录错误
    }
    */
  };

  // 取消注册快捷键（暂时禁用）
  const unregisterShortcuts = async () => {
    console.log('🔄 全局快捷键取消注册已暂时禁用');
    
    // TODO: 修复全局快捷键问题后重新启用
    // 暂时注释掉全局快捷键取消注册
    /*
    try {
      await safeTauriInvoke('unregister_global_shortcut', {
        shortcut: shortcuts.toggleVisibility
      });
      
      // ... 其他快捷键取消注册
      
      console.log('全局快捷键取消注册成功');
    } catch (error) {
      console.error('取消注册全局快捷键失败:', error);
    }
    */
  };

  // 处理快捷键事件（浏览器内键盘事件监听）
  const handleKeyDown = (event: KeyboardEvent) => {
    const { ctrlKey, shiftKey, altKey, key } = event;
    
    // 构建快捷键字符串
    const keyCombo = [
      ctrlKey && 'Ctrl',
      shiftKey && 'Shift', 
      altKey && 'Alt',
      key.toUpperCase()
    ].filter(Boolean).join('+');
    
    console.log('⌨️ 检测到按键:', keyCombo);
    
    // 匹配快捷键并执行相应操作
    const normalizedToggleVisibility = shortcuts.toggleVisibility.replace(/\s/g, '');
    const normalizedIncreaseOpacity = shortcuts.increaseOpacity.replace(/\s/g, '');
    const normalizedDecreaseOpacity = shortcuts.decreaseOpacity.replace(/\s/g, '');
    const normalizedToggleDisguise = shortcuts.toggleDisguise.replace(/\s/g, '');
    
    if (keyCombo === normalizedToggleVisibility) {
      event.preventDefault();
      console.log('🔄 切换窗口可见性');
      setIsVisible(!isVisible);
    } else if (keyCombo === normalizedIncreaseOpacity) {
      event.preventDefault();
      const newOpacity = Math.min(1, opacity + 0.1);
      console.log('⬆️ 增加透明度:', newOpacity);
      setOpacity(newOpacity);
    } else if (keyCombo === normalizedDecreaseOpacity) {
      event.preventDefault();
      const reducedOpacity = Math.max(0.1, opacity - 0.1);
      console.log('⬇️ 减少透明度:', reducedOpacity);
      setOpacity(reducedOpacity);
    } else if (keyCombo === normalizedToggleDisguise) {
      event.preventDefault();
      const newMode = currentMode === 'disguise' ? 'reading' : 'disguise';
      console.log('🎭 切换伪装模式:', newMode);
      setCurrentMode(newMode);
    }
  };

  useEffect(() => {
    console.log('🚀 GlobalShortcuts 组件初始化');
    
    // 注册快捷键（暂时禁用全局快捷键）
    registerShortcuts();
    
    // 添加浏览器键盘事件监听
    if (typeof window !== 'undefined') {
      console.log('📝 添加键盘事件监听器');
      window.addEventListener('keydown', handleKeyDown);
    }
    
    // 清理函数
    return () => {
      console.log('🧹 清理 GlobalShortcuts 组件');
      unregisterShortcuts();
      if (typeof window !== 'undefined') {
        window.removeEventListener('keydown', handleKeyDown);
      }
    };
  }, [shortcuts, opacity, isVisible, currentMode, setOpacity, setIsVisible, setCurrentMode]);

  // 这个组件不渲染任何UI
  return null;
};

export default GlobalShortcuts;